using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Text;
using HslCommunication;

namespace Catastrophe.AutoSulution.TaskM
{
	public class BaseLogic
	{
		/// <summary>
		/// 当前条件判断信息
		/// </summary>
		private string _successInfo = "";

		/// <summary>
		/// 当前条件判断信息
		/// </summary>
		private string _failedInfo = "";

		/// <summary>
		/// 当前条件判断信息
		/// </summary>
		private string _summaryInfo = "";

		/// <summary>
		/// 最大记录条件或者等待信息字符串长度
		/// 正常情况是无法达到最大字符串长度的，
		/// 除非使用IfAnd或者IfOr方法不当，每次都是追加上次的信息
		/// </summary>
		private const int MaxRecordStrCount = 10240;

		/// <summary>
		/// 任务步骤详情
		/// </summary>
		private string _taskStepDetails = "";

		/// <summary>
		/// 缓存
		/// </summary>
		private Dictionary<string, Func<TaskComplete, TaskComplete>> _dicFuncCache = new Dictionary<string, Func<TaskComplete, TaskComplete>>();

		private Dictionary<string, ScheduleAttribute> _dicScheduleAbCache = new Dictionary<string, ScheduleAttribute>();

		/// <summary>
		/// 任务模式监控信息
		/// </summary>
		private List<TaskModeMonitorInfo> _taskModeDetails = new List<TaskModeMonitorInfo>();

		/// <summary>
		/// 当前任务标题
		/// </summary>
		private string _taskTittle = "";

		/// <summary>
		///     步骤提示
		///     根据ConditionBufferLen记录缓存数量，持续输出判断通过条件信息以及执行方法信息
		/// </summary>
		public Action<string> StepTipsHandler { get; set; }

		/// <summary>
		///     不满足执行条件的等待信息
		/// </summary>
		public string WaitInfo { get; set; } = "";


		/// <summary>
		/// 当前执行段条件判断
		/// </summary>
		public string ConditionValue { get; set; } = "";


		/// <summary>
		/// 条件实体（扩展WaitInfo）
		/// </summary>
		public BaseCase CaseInfoNow { get; set; } = new BaseCase();


		/// <summary>
		/// 执行成功条件缓存保存数量
		/// </summary>
		public int ConditionBufferLen { get; set; }

		/// <summary>
		/// 执行成功条件判断缓存
		/// </summary>
		public Queue<string> SuccessConditionBuffer { get; set; }

		/// <summary>
		/// 条件缓存记录数量
		/// </summary>
		public int ConditionCacheCountSet { get; set; }

		/// <summary>
		/// 条件记录缓存
		/// </summary>
		public Queue<BaseCase> ConditionCache { get; set; }

		/// <summary>
		/// 成功结果
		/// </summary>
		public OperateResult SuccessResult => new OperateResult
		{
			IsSuccess = true,
			Message = ""
		};

		/// <summary>
		/// 设置任务标题用于分割步骤和描述信息的标识如“1.准备判断”
		/// 通过‘.’分割
		/// </summary>
		public char TittleIndexFlag { get; set; } = '.';


		/// <summary>
		/// 当前时间
		/// </summary>
		public DateTime GetTimeNow => DateTime.Parse(DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss"));

		/// <summary>
		/// 条件信息
		/// </summary>
		public Case Case => new Case();

		public BaseLogic()
		{
			this.SuccessConditionBuffer = new Queue<string>();
			this.ConditionCache = new Queue<BaseCase>();
		}

		/// <summary>
		/// 设置任务步骤详情
		/// </summary>
		/// <param name="details"></param>
		public void SetTaskStepDetails(string details)
		{
			this._taskStepDetails = details;
		}

		/// <summary>
		/// 清空任务步骤详情
		/// </summary>
		public void ClearTaskStepDetails()
		{
			this._taskStepDetails = "";
		}

		/// <summary>
		/// 执行方法发生了改变
		/// </summary>
		public void ExcuteMehtodChanged()
		{
			this.ClearTaskStepDetails();
			this.ClearTaskMonitorInfo();
		}

		/// <summary>
		/// 执行之前
		/// </summary>
		public void BeforeExcute(ScheduleMethodInfo value, TaskComplete taskResult)
		{
		}

		/// <summary>
		/// 执行之后
		/// </summary>
		public void AfterExcute(ScheduleMethodInfo value, TaskComplete taskResult)
		{
			this.BuildCaseInfo();
		}

		/// <summary>
		///     控制流程提示
		/// </summary>
		/// <param name="action">委托方法</param>
		/// <param name="result">执行结果</param>
		/// <returns></returns>
		public Tuple<bool, string> Tips(Func<TaskComplete, TaskComplete> action, OperateResult result)
		{
			MethodInfo method = action.Method;
			string value = (result.IsSuccess ? "执行成功" : ("执行失败" + result.Message));
			ScheduleAttribute scheduleAttribute = Attribute.GetCustomAttribute(method, typeof(ScheduleAttribute)) as ScheduleAttribute;
			if (scheduleAttribute != null)
			{
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(19, 5);
				defaultInterpolatedStringHandler.AppendLiteral("步骤编号:");
				defaultInterpolatedStringHandler.AppendFormatted(scheduleAttribute.Index);
				defaultInterpolatedStringHandler.AppendLiteral(" 描述:");
				defaultInterpolatedStringHandler.AppendFormatted(scheduleAttribute.Describe);
				defaultInterpolatedStringHandler.AppendLiteral(" 执行状态:");
				defaultInterpolatedStringHandler.AppendFormatted(value);
				defaultInterpolatedStringHandler.AppendLiteral(" 时间:");
				defaultInterpolatedStringHandler.AppendFormatted(DateTime.Now, "yyyy/MM/dd HH:mm:ss:fff");
				defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
				string text = defaultInterpolatedStringHandler.ToStringAndClear();
				string obj = this.StepMsgRecord(text);
				this.StepTipsHandler?.Invoke(obj);
				return new Tuple<bool, string>(result.IsSuccess, text);
			}
			return new Tuple<bool, string>(result.IsSuccess, "方法未标记ScheduleAttribute");
		}

		/// <summary>
		///     自定义消息
		/// </summary>
		/// <param name="index">步骤编号</param>
		/// <param name="msg">定义消息</param>
		/// <param name="result">执行结果</param>
		/// <returns></returns>
		public Tuple<bool, string> Tips(ushort index, string msg, OperateResult result)
		{
			string text = "";
			if (result != null)
			{
				text = (result.IsSuccess ? "执行成功" : ("执行失败" + result.Message));
				DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(19, 5);
				defaultInterpolatedStringHandler.AppendLiteral("步骤编号:");
				defaultInterpolatedStringHandler.AppendFormatted(index);
				defaultInterpolatedStringHandler.AppendLiteral(" 描述:");
				defaultInterpolatedStringHandler.AppendFormatted(msg);
				defaultInterpolatedStringHandler.AppendLiteral(" 执行状态:");
				defaultInterpolatedStringHandler.AppendFormatted(text);
				defaultInterpolatedStringHandler.AppendLiteral(" 时间:");
				defaultInterpolatedStringHandler.AppendFormatted(DateTime.Now, "yyyy/MM/dd HH:mm:ss:fff");
				defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
				string text2 = defaultInterpolatedStringHandler.ToStringAndClear();
				string obj = this.StepMsgRecord(text2);
				this.StepTipsHandler?.Invoke(obj);
				return new Tuple<bool, string>(result.IsSuccess, text2);
			}
			text = "OperateResult为null";
			return new Tuple<bool, string>(item1: false, text);
		}

		/// <summary>
		///     执行完成方法信息格式化
		/// </summary>
		/// <param name="taskComplete">任务方法参数以及返回</param>
		/// <returns></returns>
		public string TaskCompleteFormat(TaskComplete taskComplete)
		{
			DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(25, 14);
			defaultInterpolatedStringHandler.AppendLiteral("方法名称:");
			defaultInterpolatedStringHandler.AppendFormatted(taskComplete.MethodName);
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			defaultInterpolatedStringHandler.AppendLiteral("编号:");
			defaultInterpolatedStringHandler.AppendFormatted(taskComplete.ScheduleAb.Index);
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			defaultInterpolatedStringHandler.AppendLiteral("描述:");
			defaultInterpolatedStringHandler.AppendFormatted(taskComplete.ScheduleAb.Describe);
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			defaultInterpolatedStringHandler.AppendLiteral("执行状态:");
			defaultInterpolatedStringHandler.AppendFormatted(taskComplete.RunStatus.ToString());
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			defaultInterpolatedStringHandler.AppendLiteral("异常:");
			defaultInterpolatedStringHandler.AppendFormatted(taskComplete.Exception?.ToString());
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			defaultInterpolatedStringHandler.AppendLiteral("标识:");
			defaultInterpolatedStringHandler.AppendFormatted(taskComplete.Flag);
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			defaultInterpolatedStringHandler.AppendLiteral("时间:");
			defaultInterpolatedStringHandler.AppendFormatted(DateTime.Now, "yyyy/MM/dd HH:mm:ss:fff");
			defaultInterpolatedStringHandler.AppendFormatted(Environment.NewLine);
			return defaultInterpolatedStringHandler.ToStringAndClear();
		}

		/// <summary>
		/// 执行完成方法信息格式化
		/// </summary>
		/// <param name="taskComplete">任务方法参数以及返回</param>
		/// <returns></returns>
		public static TaskDescribeEntity TaskCompleteEntityFormat(TaskComplete taskComplete)
		{
			return new TaskDescribeEntity
			{
				MethodName = taskComplete.MethodName,
				Index = taskComplete.ScheduleAb.Index,
				Describe = taskComplete.ScheduleAb.Describe,
				RunStatus = taskComplete.RunStatus.ToString(),
				Error = taskComplete.Exception,
				Flag = taskComplete.Flag,
				OprResult = taskComplete.OprResult,
				ProcessValue = taskComplete.ProcessValue
			};
		}

		/// <summary>
		/// 任务提示-生成任务参数
		/// </summary>
		/// <param name="action">委托方法</param>
		/// <param name="result">执行结果</param>
		/// <param name="sucessStatus">执行成功状态</param>
		/// <param name="failedStatus">执行失败状态</param>
		/// <param name="successFlag">执行成功返回标识</param>
		/// <param name="failedFlag">执行失败标识</param>
		/// <param name="breakToFunc">RunStatusEnum=Break的时候跳转的目标方法</param>
		/// <returns></returns>
		public TaskComplete TaskTips(Func<TaskComplete, TaskComplete> action, OperateResult result, RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int successFlag = -1, int failedFlag = -1, Func<TaskComplete, TaskComplete> breakToFunc = null, int processValue = 0)
		{
			Tuple<bool, string> tuple = this.Tips(action, result);
			return tuple.Item1 ? new TaskComplete
			{
				RunStatus = sucessStatus,
				Flag = successFlag,
				DstFunc = breakToFunc,
				ProcessValue = processValue
			} : new TaskComplete
			{
				RunStatus = failedStatus,
				Flag = failedFlag,
				DstFunc = breakToFunc,
				ProcessValue = processValue
			};
		}

		/// <summary>
		///    任务提示-生成任务参数
		/// </summary>
		/// <param name="index">步骤编号</param>
		/// <param name="msg">定义消息</param>
		/// <param name="result">执行结果</param>
		/// <param name="sucessStatus">执行成功状态</param>
		/// <param name="failedStatus">执行失败状态</param>
		/// <param name="successFlag">执行成功返回标识</param>
		/// <param name="failedFlag">执行失败标识</param>
		/// <param name="breakToFunc">RunStatusEnum=Break的时候跳转的目标方法</param>
		/// <param name="param"></param>
		/// <returns></returns>
		public TaskComplete TaskTips(ushort index, string msg, OperateResult result, RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int? successFlag = null, int? failedFlag = null, object param = null, Func<TaskComplete, TaskComplete> breakToFunc = null, int processValue = 0)
		{
			if (successFlag.HasValue && !failedFlag.HasValue)
			{
				failedFlag = successFlag;
			}
			Tuple<bool, string> tuple = this.Tips(index, msg, result);
			return tuple.Item1 ? new TaskComplete
			{
				RunStatus = sucessStatus,
				Flag = successFlag,
				Param = param,
				Message = "",
				TaskStepDetails = this._taskStepDetails,
				DstFunc = breakToFunc,
				OprResult = result,
				ProcessValue = processValue
			} : new TaskComplete
			{
				RunStatus = failedStatus,
				Flag = failedFlag,
				Param = param,
				Message = tuple.Item2,
				TaskStepDetails = this._taskStepDetails,
				DstFunc = breakToFunc,
				OprResult = result,
				ProcessValue = processValue
			};
		}

		/// <summary>
		/// 任务提交
		/// 1.根据方法特性和additionalDescribe参数提供任务描述
		/// 2.更新进度，默认以方法修饰特性的字段为主，也可以通过customStepIndex参数自定义
		/// 3.根据OperateResult结果指明执行成功或者失败的循环动作
		/// 4.提供日志记录
		/// </summary>
		/// <param name="scheduleAb">方法修饰特性</param>
		/// <param name="taskParam">任务参数</param>
		/// <param name="result">结果</param>
		/// <param name="additionalDescribe">附加说明</param>
		/// <param name="sucessStatus">执行成功后执行动作</param>
		/// <param name="failedStatus">执行失败后执行动作</param>
		/// <param name="customStepIndex">自定义当前步骤编号</param>
		/// <param name="debugFlag">调试标识（模拟设置OperateResult IsSucess标识）</param>
		/// <param name="breakToFunc">RunStatusEnum=Break的时候跳转的目标方法</param>
		/// <returns></returns>
		public TaskComplete TaskCommit(ScheduleAttribute scheduleAb, object taskParam, OperateResult result, string additionalDescribe = "", RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int? customStepIndex = null, bool? debugFlag = null, Func<TaskComplete, TaskComplete> breakToFunc = null)
		{
			if (scheduleAb == null)
			{
				throw new ArgumentNullException("scheduleAb");
			}
			if (result == null)
			{
				throw new ArgumentNullException("result");
			}
			if (debugFlag.HasValue && result != null)
			{
				result.IsSuccess = debugFlag.Value;
			}
			int num = customStepIndex ?? scheduleAb.Index;
			if (!string.IsNullOrWhiteSpace(additionalDescribe))
			{
				additionalDescribe = "-" + additionalDescribe;
			}
			string msg = scheduleAb.Describe + additionalDescribe;
			this.AddRecord(scheduleAb, result, "获取当前任务");
			ushort index = scheduleAb.Index;
			int processValue = num;
			return this.TaskTips(index, msg, result, sucessStatus, failedStatus, null, null, taskParam, breakToFunc, processValue);
		}

		/// <summary>
		/// 任务提交-只能在调度方法上下文使用否则无法获取CallerMemberName
		/// </summary>
		/// <param name="taskParam">任务参数</param>
		/// <param name="result">结果</param>
		/// <param name="additionalDescribe">附加说明</param>
		/// <param name="sucessStatus">执行成功后执行动作</param>
		/// <param name="failedStatus">执行失败后执行动作</param>
		/// <param name="customStepIndex">自定义当前步骤编号</param>
		/// <param name="debugFlag">调试标识（模拟设置OperateResult IsSucess标识）</param>
		/// <param name="breakToFunc">RunStatusEnum=Break的时候跳转的目标方法</param>
		/// <param name="methodName"></param>
		/// <returns></returns>
		public TaskComplete TaskCommit(object taskParam, OperateResult result, string additionalDescribe = "", RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int? customStepIndex = null, bool debugFlag = false, Func<TaskComplete, TaskComplete> breakToFunc = null, [CallerMemberName] string methodName = "")
		{
			if (debugFlag && result != null)
			{
				result.IsSuccess = true;
			}
			ScheduleAttribute methodDescribe = this.GetMethodDescribe(methodName);
			return this.TaskCommit(methodDescribe, taskParam, result, additionalDescribe, sucessStatus, failedStatus, customStepIndex, null, breakToFunc);
		}

		/// <summary>
		/// 任务提交-只能在调度方法上下文使用否则无法获取CallerMemberName
		/// 适用于：条件已经判断成功
		/// </summary>
		/// <param name="taskParam">任务参数</param>
		/// <param name="additionalDescribe">附加说明</param>
		/// <param name="sucessStatus">执行成功动作枚举</param>
		/// <param name="failedStatus">执行失败动作枚举</param>
		/// <param name="customStepIndex">自定义步骤索引</param>
		/// <param name="breakToFunc">RunStatusEnum=Break的时候跳转的目标方法</param>
		/// <param name="methodName"></param>
		/// <returns></returns>
		public TaskComplete TaskCommit(object taskParam, string additionalDescribe = "", RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int? customStepIndex = null, Func<TaskComplete, TaskComplete> breakToFunc = null, [CallerMemberName] string methodName = "")
		{
			return this.TaskCommit(taskParam, this.SuccessResult, additionalDescribe, sucessStatus, failedStatus, customStepIndex, debugFlag: false, breakToFunc, methodName);
		}

		public TaskComplete TaskCommit(Func<TaskComplete, TaskComplete> func, object taskParam, OperateResult result, string additionalDescribe = "", RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int? customStepIndex = null, bool debugFlag = false, Func<TaskComplete, TaskComplete> breakToFunc = null)
		{
			ScheduleAttribute methodDescribe = this.GetMethodDescribe(func);
			return this.TaskCommit(methodDescribe, taskParam, result, additionalDescribe, sucessStatus, failedStatus, customStepIndex, debugFlag, breakToFunc);
		}

		public TaskComplete TaskCommit(Func<TaskComplete, TaskComplete> func, object taskParam, string additionalDescribe = "", RunStatusEnum sucessStatus = RunStatusEnum.Continue, RunStatusEnum failedStatus = RunStatusEnum.Wait, int? customStepIndex = null, Func<TaskComplete, TaskComplete> breakToFunc = null)
		{
			return this.TaskCommit(func, taskParam, this.SuccessResult, additionalDescribe, sucessStatus, failedStatus, customStepIndex, debugFlag: false, breakToFunc);
		}

		/// <summary>
		/// 返回等待
		/// 提供标识、任务参数
		/// </summary>
		/// <param name="flag"></param>
		/// <param name="param"></param>
		/// <returns></returns>
		public TaskComplete Wait(int? flag = null, object param = null)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Wait,
				Flag = flag,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回等待
		/// 提供任务参数
		/// </summary>
		/// <param name="param"></param>
		/// <returns></returns>
		public TaskComplete Wait(object param)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Wait,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回等待
		/// 提供TaskComplete
		/// </summary>
		/// <param name="lastTask"></param>
		/// <returns></returns>
		public TaskComplete Wait(TaskComplete lastTask)
		{
			if (lastTask == null)
			{
				return new TaskComplete
				{
					RunStatus = RunStatusEnum.Wait,
					TaskStepDetails = this._taskStepDetails
				};
			}
			lastTask.RunStatus = RunStatusEnum.Wait;
			lastTask.TaskStepDetails = this._taskStepDetails;
			return lastTask;
		}

		/// <summary>
		/// 返回中断
		/// 提供标识、任务参数
		/// </summary>
		/// <param name="flag"></param>
		/// <param name="param"></param>
		/// <returns></returns>
		public TaskComplete Break(int? flag = null, object param = null)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Break,
				Flag = flag,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回中断
		/// 提供任务参数
		/// </summary>
		/// <param name="param">参数</param>
		/// <returns></returns>
		public TaskComplete Break(object param)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Break,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回中断
		/// 提供TaskComplete
		/// </summary>
		/// <param name="lastTask">任务方法参数以及返回</param>
		/// <returns></returns>
		public TaskComplete Break(TaskComplete lastTask)
		{
			lastTask.RunStatus = RunStatusEnum.Break;
			lastTask.TaskStepDetails = this._taskStepDetails;
			return lastTask;
		}

		/// <summary>
		/// 返回跳转到
		/// </summary>
		/// <param name="func">方法</param>
		/// <param name="flag">标识</param>
		/// <param name="param">参数</param>
		/// <returns></returns>
		public TaskComplete BreakTo(Func<TaskComplete, TaskComplete> func, int? flag = null, object param = null)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Break,
				Flag = flag,
				DstFunc = func,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回结束
		/// 提供标识、任务参数
		/// </summary>
		/// <param name="flag">标识</param>
		/// <param name="param">参数</param>
		/// <returns></returns>
		public TaskComplete Finished(int? flag = null, object param = null)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Finished,
				Flag = flag,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回结束
		/// 提供任务参数
		/// </summary>
		/// <param name="param">参数</param>
		/// <returns></returns>
		public TaskComplete Finished(object param)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Finished,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回结束
		/// 提供TaskComplete
		/// </summary>
		/// <param name="lastTask">任务方法参数以及返回</param>
		/// <returns></returns>
		public TaskComplete Finished(TaskComplete lastTask)
		{
			lastTask.RunStatus = RunStatusEnum.Finished;
			lastTask.TaskStepDetails = this._taskStepDetails;
			return lastTask;
		}

		/// <summary>
		/// 返回暂停
		/// 提供标识、任务参数
		/// </summary>
		/// <param name="flag">标识</param>
		/// <returns></returns>
		public TaskComplete Stop(int? flag = null, object param = null)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Stop,
				Flag = flag,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回暂停
		/// 提供任务参数
		/// </summary>
		/// <param name="flag">标识</param>
		/// <returns></returns>
		public TaskComplete Stop(object param)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Stop,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回暂停
		/// 提供TaskComplete
		/// </summary>
		/// <param name="lastTask">任务方法参数以及返回</param>
		/// <returns></returns>
		public TaskComplete Stop(TaskComplete lastTask)
		{
			lastTask.RunStatus = RunStatusEnum.Stop;
			lastTask.TaskStepDetails = this._taskStepDetails;
			return lastTask;
		}

		/// <summary>
		/// 返回继续
		/// </summary>
		/// <param name="flag">标识</param>
		/// <returns></returns>
		public TaskComplete Continue(int? flag = null, object param = null)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Continue,
				Flag = flag,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回继续
		/// 提供任务参数
		/// </summary>
		/// <param name="param">参数</param>
		/// <returns></returns>
		public TaskComplete Continue(object param)
		{
			return new TaskComplete
			{
				RunStatus = RunStatusEnum.Continue,
				Param = param,
				TaskStepDetails = this._taskStepDetails
			};
		}

		/// <summary>
		/// 返回继续
		/// 提供TaskComplete
		/// </summary>
		/// <param name="lastTask">任务方法参数以及返回</param>
		/// <returns></returns>
		public TaskComplete Continue(TaskComplete lastTask)
		{
			lastTask.RunStatus = RunStatusEnum.Continue;
			lastTask.TaskStepDetails = this._taskStepDetails;
			return lastTask;
		}

		/// <summary>
		/// 判断、执行、消息记录
		/// </summary>
		/// <param name="msg">消息</param>
		/// <returns></returns>
		private string StepMsgRecord(string msg)
		{
			if (this.ConditionBufferLen <= 0)
			{
				return msg;
			}
			if (this.SuccessConditionBuffer.Count > this.ConditionBufferLen)
			{
				this.SuccessConditionBuffer.Dequeue();
			}
			this.SuccessConditionBuffer.Enqueue(msg);
			StringBuilder stringBuilder = new StringBuilder();
			foreach (string item in this.SuccessConditionBuffer)
			{
				stringBuilder.Append(item + Environment.NewLine);
			}
			return stringBuilder.ToString();
		}

		/// <summary>
		/// 条件缓存记录
		/// </summary>
		/// <param name="caseValue">消息</param>
		/// <returns></returns>
		private void CaseCacheRecord(BaseCase caseValue)
		{
			if (this.ConditionCacheCountSet > 0)
			{
				if (this.ConditionCache.Count > this.ConditionCacheCountSet)
				{
					this.ConditionCache.Dequeue();
				}
				this.ConditionCache.Enqueue(caseValue);
			}
		}

		/// <summary>
		/// 判断条件合并
		/// </summary>
		/// <param name="dicBuf">条件集合</param>
		/// <returns></returns>
		public Dictionary<string, bool> DicCombine(params Dictionary<string, bool>[] dicBuf)
		{
			if (dicBuf == null)
			{
				throw new ArgumentNullException("dicBuf");
			}
			Dictionary<string, bool> dictionary = new Dictionary<string, bool>();
			foreach (Dictionary<string, bool> dictionary2 in dicBuf)
			{
				foreach (string key in dictionary2.Keys)
				{
					if (dictionary.ContainsKey(key))
					{
						throw new Exception("key重复" + key);
					}
					dictionary.Add(key, dictionary2[key]);
				}
			}
			return dictionary;
		}

		/// <summary>
		/// 任务模式监控信息记录
		/// </summary>
		/// <param name="dic">条件集合</param>
		private void TaskModeInfoRecord(Dictionary<string, bool> dic)
		{
			if (string.IsNullOrWhiteSpace(this._taskTittle))
			{
				return;
			}
			TaskModeMonitorInfo taskModeMonitorInfo = this._taskModeDetails.FirstOrDefault((TaskModeMonitorInfo x) => x.Tittle == this._taskTittle);
			if (taskModeMonitorInfo == null)
			{
				return;
			}
			taskModeMonitorInfo.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff");
			foreach (string key in dic.Keys)
			{
				if (!taskModeMonitorInfo.DicCondition.ContainsKey(key))
				{
					taskModeMonitorInfo.DicCondition.Add(key, new ConditionEntity
					{
						ConInfo = key,
						ConRet = dic[key]
					});
				}
				else
				{
					taskModeMonitorInfo.DicCondition[key].ConRet = dic[key];
				}
			}
		}

		/// <summary>
		/// 任务模式监控信息记录
		/// </summary>
		/// <param name="caseValue">条件集合</param>
		private void TaskModeInfoRecord(Case caseValue)
		{
			if (string.IsNullOrWhiteSpace(this._taskTittle))
			{
				return;
			}
			TaskModeMonitorInfo taskModeMonitorInfo = this._taskModeDetails.FirstOrDefault((TaskModeMonitorInfo x) => x.Tittle == this._taskTittle);
			if (taskModeMonitorInfo == null)
			{
				return;
			}
			taskModeMonitorInfo.TimeStamp = DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff");
			taskModeMonitorInfo.Summary = caseValue.Summary;
			foreach (Case @case in caseValue.CaseList)
			{
				if (!taskModeMonitorInfo.DicCondition.ContainsKey(@case.Entity.ConInfo))
				{
					taskModeMonitorInfo.DicCondition.Add(@case.Entity.ConInfo, @case.Entity);
				}
				else
				{
					taskModeMonitorInfo.DicCondition[@case.Entity.ConInfo] = @case.Entity;
				}
			}
		}

		/// <summary>
		/// 显示状态的格式化
		/// </summary>
		/// <param name="value"></param>
		/// <returns></returns>
		private static string StateFormat(bool value)
		{
			return value ? "状态:YES" : "状态:NO";
		}

		/// <summary>
		/// 条件判断并记录判断条件
		/// </summary>
		/// <param name="dic">条件集合</param>
		/// <param name="successInfo">条件格式化</param>
		/// <param name="saveCondition">是否保持当前条件信息</param>
		/// <param name="isAdd">是否将当前条件信息与上次叠加</param>
		/// <returns></returns>
		public bool IfAnd(Dictionary<string, bool> dic, ref string successInfo, bool saveCondition = true, bool isAdd = false)
		{
			if (dic == null)
			{
				throw new ArgumentNullException("dic");
			}
			this.TaskModeInfoRecord(dic);
			bool flag = true;
			string text = "";
			foreach (string key in dic.Keys)
			{
				string text2 = key + " " + BaseLogic.StateFormat(dic[key]) + Environment.NewLine;
				if (!dic[key])
				{
					text += text2;
				}
				successInfo += text2;
				flag = flag && dic[key];
			}
			flag = dic.Count > 0 && flag;
			this.CaseInfoLog(new BaseCase
			{
				SuccessInfo = successInfo,
				FailedInfo = text,
				Summary = "",
				Result = flag
			}, saveCondition, isAdd);
			return flag;
		}

		/// <summary>
		/// 条件判断并记录判断条件
		/// </summary>
		/// <param name="dic">条件集合</param>
		/// <param name="saveCondition">是否保持当前条件信息</param>
		/// <param name="isAdd">是否将当前条件信息与上次叠加</param>
		/// <param name="debugFlag">调试标识</param>
		/// <returns></returns>
		public bool IfAnd(Dictionary<string, bool> dic, bool saveCondition = true, bool isAdd = false, bool debugFlag = false)
		{
			string successInfo = "";
			bool flag = this.IfAnd(dic, ref successInfo, saveCondition, isAdd);
			return debugFlag || flag;
		}

		/// <summary>
		/// 条件判断并记录判断条件
		/// </summary>
		/// <param name="dic">条件信息</param>
		/// <param name="saveCondition">是否保持当前条件信息</param>
		/// <param name="isAdd">是否将当前条件信息与上次叠加</param>
		/// <param name="debugFlag">调试标识</param>
		/// <returns></returns>
		[Obsolete("use When(Case[] instead!)")]
		public bool IfOr(Dictionary<string, bool> dic, bool saveCondition = true, bool isAdd = false, bool debugFlag = false)
		{
			if (dic == null)
			{
				throw new ArgumentNullException("dic");
			}
			bool flag = false;
			string text = "";
			string text2 = "";
			foreach (string key in dic.Keys)
			{
				string text3 = key + " " + BaseLogic.StateFormat(dic[key]) + Environment.NewLine;
				if (!dic[key])
				{
					text2 += text3;
				}
				text += text3;
				flag = flag || dic[key];
			}
			flag = dic.Count > 0 && flag;
			text = (flag ? ("满足条件:" + Environment.NewLine + text) : ("不满足条件:" + Environment.NewLine + text)) + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff");
			this.CaseInfoLog(new BaseCase
			{
				SuccessInfo = text,
				FailedInfo = text2,
				Summary = "",
				Result = flag
			}, saveCondition, isAdd);
			return debugFlag || flag;
		}

		/// <summary>
		/// 当...相对于IfAnd与IfOr
		/// </summary>
		/// <param name="caseValue">条件信息</param>
		/// <param name="saveCondition">是否保留条件</param>
		/// <param name="isAdd">只有后面连续判断的时候才会有可能设置true</param>
		/// <param name="debugFlag">调试标识</param>
		/// <returns></returns>
		/// <exception cref="T:System.ArgumentNullException"></exception>
		public bool When(Case caseValue, bool saveCondition = true, bool isAdd = false, bool debugFlag = false)
		{
			if (caseValue == null)
			{
				throw new ArgumentNullException("caseValue");
			}
			if (caseValue.CaseList.Count == 0)
			{
				caseValue = caseValue.DeepCopy();
			}
			StringBuilder stringBuilder = new StringBuilder();
			StringBuilder stringBuilder2 = new StringBuilder();
			StringBuilder stringBuilder3 = new StringBuilder();
			foreach (Case @case in caseValue.CaseList)
			{
				if (@case.Entity.ConRet)
				{
					StringBuilder stringBuilder4 = stringBuilder;
					StringBuilder stringBuilder5 = stringBuilder4;
					StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(1, 3, stringBuilder4);
					handler.AppendFormatted(@case.Entity.ConInfo);
					handler.AppendLiteral(" ");
					handler.AppendFormatted(BaseLogic.StateFormat(@case.Entity.ConRet));
					handler.AppendFormatted(Environment.NewLine);
					stringBuilder5.Append(ref handler);
				}
				else
				{
					string value = (string.IsNullOrWhiteSpace(@case.Entity.Details) ? "" : ("详情:" + @case.Entity.Details));
					StringBuilder stringBuilder4 = stringBuilder2;
					StringBuilder stringBuilder6 = stringBuilder4;
					StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(2, 4, stringBuilder4);
					handler.AppendFormatted(@case.Entity.ConInfo);
					handler.AppendLiteral(" ");
					handler.AppendFormatted(BaseLogic.StateFormat(@case.Entity.ConRet));
					handler.AppendLiteral(" ");
					handler.AppendFormatted(value);
					handler.AppendFormatted(Environment.NewLine);
					stringBuilder6.Append(ref handler);
				}
				if (!string.IsNullOrWhiteSpace(@case.Entity.Details))
				{
					StringBuilder stringBuilder4 = stringBuilder3;
					StringBuilder stringBuilder7 = stringBuilder4;
					StringBuilder.AppendInterpolatedStringHandler handler = new StringBuilder.AppendInterpolatedStringHandler(1, 3, stringBuilder4);
					handler.AppendFormatted(@case.Entity.ConInfo);
					handler.AppendLiteral(":");
					handler.AppendFormatted(@case.Entity.Details);
					handler.AppendFormatted(Environment.NewLine);
					stringBuilder7.Append(ref handler);
				}
			}
			caseValue.SuccessInfo = stringBuilder.ToString();
			caseValue.FailedInfo = stringBuilder2.ToString();
			caseValue.Entity.Details = stringBuilder3.ToString();
			this.TaskModeInfoRecord(caseValue);
			this.CaseInfoLog(caseValue, saveCondition, isAdd);
			return debugFlag || caseValue.Result;
		}

		/// <summary>
		/// 生成条件信息
		/// </summary>
		private void BuildCaseInfo()
		{
			string successInfo = this._successInfo;
			if (successInfo != null && successInfo.Length >= 10240)
			{
				this._successInfo = "";
				this.ConditionValue = "";
				this.CaseInfoNow.SuccessInfo = "";
				this.CaseInfoNow.Summary = "";
			}
			this.ConditionValue = this._successInfo;
			this.WaitInfo = this._failedInfo;
			this.CaseInfoNow.SuccessInfo = this._successInfo;
			this.CaseInfoNow.FailedInfo = this._failedInfo;
			this.CaseInfoNow.Summary = this._summaryInfo;
			this._failedInfo = "";
			this._successInfo = "";
			this._summaryInfo = "";
		}

		/// <summary>
		/// 条件信息扩展
		/// </summary>
		/// <param name="msg"></param>
		/// <returns></returns>
		private string CondiInfoExtend(string msg)
		{
			return msg + DateTime.Now.ToString("yyyy/MM/dd HH:mm:ss:fff") + Environment.NewLine;
		}

		/// <summary>
		/// 条件信息日志
		/// </summary>
		/// <param name="baseCase">条件信息</param>
		/// <param name="saveCondition">保留条件</param>
		/// <param name="isAdd">新增</param>
		private void CaseInfoLog(BaseCase baseCase, bool saveCondition, bool isAdd)
		{
			if (isAdd)
			{
				if (!string.IsNullOrWhiteSpace(baseCase.SuccessInfo))
				{
					this._successInfo += this.CondiInfoExtend(baseCase.SuccessInfo);
				}
				if (!string.IsNullOrWhiteSpace(baseCase.Summary))
				{
					this._summaryInfo += this.CondiInfoExtend(baseCase.Summary);
				}
				if (!string.IsNullOrWhiteSpace(baseCase.FailedInfo))
				{
					this._failedInfo += this.CondiInfoExtend(baseCase.FailedInfo);
				}
			}
			else if (saveCondition)
			{
				this._successInfo = baseCase.SuccessInfo;
				this._summaryInfo = baseCase.Summary;
				this._failedInfo = baseCase.FailedInfo;
			}
			this.CaseCacheRecord(baseCase);
			if (baseCase.Result)
			{
				this.StepMsgRecord(baseCase.SuccessInfo);
			}
		}

		/// <summary>
		/// 清空记录的任务监控信息
		/// </summary>
		public void ClearTaskMonitorInfo()
		{
			this._taskModeDetails.Clear();
		}

		/// <summary>
		/// 设置任务标题
		/// </summary>
		/// <param name="tittle"></param>
		public void SetTitle(string tittle)
		{
			if (string.IsNullOrWhiteSpace(tittle))
			{
				return;
			}
			this._taskTittle = tittle;
			string[] array = tittle.Split(this.TittleIndexFlag);
			string text = "";
			string text2 = "";
			bool flag = true;
			string[] array2 = array;
			foreach (string text3 in array2)
			{
				if (flag)
				{
					if (int.TryParse(text3, out var _))
					{
						string text4 = text;
						DefaultInterpolatedStringHandler defaultInterpolatedStringHandler = new DefaultInterpolatedStringHandler(0, 2);
						defaultInterpolatedStringHandler.AppendFormatted(text3);
						defaultInterpolatedStringHandler.AppendFormatted(this.TittleIndexFlag);
						text = text4 + defaultInterpolatedStringHandler.ToStringAndClear();
					}
					else
					{
						flag = false;
						text2 += text3;
					}
				}
				else
				{
					text2 += text3;
				}
			}
			if (this._taskModeDetails.All((TaskModeMonitorInfo x) => x.Tittle != tittle))
			{
				this._taskModeDetails.Add(new TaskModeMonitorInfo
				{
					IndexFormat = text,
					TittleFormat = text2,
					Tittle = tittle,
					DicCondition = new Dictionary<string, ConditionEntity>()
				});
			}
		}

		/// <summary>
		/// 将监控信息转换DataTable
		/// </summary>
		/// <returns></returns>
		public DataTable ConvertDicToDt()
		{
			DataTable dataTable = new DataTable();
			dataTable.Columns.Add("TittleFormat");
			dataTable.Columns.Add("IndexFormat");
			dataTable.Columns.Add("ConditionDescribe");
			dataTable.Columns.Add("ConditionResult");
			dataTable.Columns.Add("ConditionDetails");
			dataTable.Columns.Add("Summary");
			dataTable.Columns.Add("TimeStamp");
			foreach (TaskModeMonitorInfo taskModeDetail in this._taskModeDetails)
			{
				foreach (string key in taskModeDetail.DicCondition.Keys)
				{
					DataRow dataRow = dataTable.NewRow();
					dataRow["TittleFormat"] = taskModeDetail.TittleFormat;
					dataRow["IndexFormat"] = taskModeDetail.IndexFormat;
					dataRow["ConditionDescribe"] = key;
					dataRow["ConditionResult"] = (taskModeDetail.DicCondition[key].ConRet ? "Yes" : "No");
					dataRow["TimeStamp"] = taskModeDetail.TimeStamp;
					dataRow["ConditionDetails"] = taskModeDetail.DicCondition[key].Details;
					dataRow["Summary"] = taskModeDetail.Summary;
					dataTable.Rows.Add(dataRow);
				}
			}
			return dataTable;
		}

		/// <summary>
		/// 获取方法的描述信息
		/// </summary>
		/// <param name="funcMethod"></param>
		/// <returns></returns>
		public ScheduleAttribute GetMethodDescribe(Func<TaskComplete, TaskComplete> funcMethod)
		{
			if (funcMethod == null)
			{
				throw new ArgumentNullException("funcMethod");
			}
			if (this._dicScheduleAbCache.ContainsKey(funcMethod.Method.Name))
			{
				return this._dicScheduleAbCache[funcMethod.Method.Name];
			}
			ScheduleAttribute scheduleAttribute = Attribute.GetCustomAttribute(funcMethod.Method, typeof(ScheduleAttribute)) as ScheduleAttribute;
			if (scheduleAttribute == null)
			{
				throw new Exception("目标方法未被ScheduleAttribute修饰");
			}
			this._dicScheduleAbCache.Add(funcMethod.Method.Name, scheduleAttribute);
			return scheduleAttribute;
		}

		/// <summary>
		/// 通过方法名称和调度对象获取方法描述信息（只能在当前方法上下文使用）
		/// </summary>
		/// <param name="methodName">方法名</param>
		/// <returns></returns>
		public ScheduleAttribute GetMethodDescribe([CallerMemberName] string methodName = "")
		{
			if (methodName == null)
			{
				throw new ArgumentNullException("methodName");
			}
			if (this._dicScheduleAbCache.ContainsKey(methodName))
			{
				return this._dicScheduleAbCache[methodName];
			}
			Func<TaskComplete, TaskComplete> funcMethod = (Func<TaskComplete, TaskComplete>)Delegate.CreateDelegate(typeof(Func<TaskComplete, TaskComplete>), this, methodName);
			return this.GetMethodDescribe(funcMethod);
		}

		/// <summary>
		/// 通过方法名称和调度对象获取一个Func
		/// </summary>
		/// <param name="methodName">方法名</param>
		/// <returns></returns>
		public Func<TaskComplete, TaskComplete> GetMethodFunc(string methodName)
		{
			if (methodName == null)
			{
				throw new ArgumentNullException("methodName");
			}
			if (this._dicFuncCache.ContainsKey(methodName))
			{
				return this._dicFuncCache[methodName];
			}
			Func<TaskComplete, TaskComplete> func = (Func<TaskComplete, TaskComplete>)Delegate.CreateDelegate(typeof(Func<TaskComplete, TaskComplete>), this, methodName);
			if (func != null)
			{
				this._dicFuncCache.Add(methodName, func);
			}
			return func;
		}

		/// <summary>
		/// 新增记录
		/// </summary>
		/// <param name="funcMethod">调度方法</param>
		/// <param name="taskDetails">任务详情</param>
		/// <param name="result">执行结果</param>
		protected void AddRecord(Func<TaskComplete, TaskComplete> funcMethod, OperateResult result, string taskDetails = "")
		{
			if (result?.IsSuccess ?? false)
			{
				result.Message = "";
			}
			string conditionValue = this.ConditionValue;
			ScheduleAttribute methodDescribe = this.GetMethodDescribe(funcMethod);
			if (methodDescribe != null)
			{
				this.TaskRecord(methodDescribe, taskDetails, conditionValue, result);
			}
		}

		/// <summary>
		/// 新增记录
		/// </summary>
		/// <param name="ab">修饰方法特性</param>
		/// <param name="result">执行结果</param>
		/// <param name="taskDetails">任务详情</param>
		protected void AddRecord(ScheduleAttribute ab, OperateResult result, string taskDetails = "")
		{
			if (ab != null)
			{
				if (result?.IsSuccess ?? false)
				{
					result.Message = "";
				}
				string conditionValue = this.ConditionValue;
				this.TaskRecord(ab, taskDetails, conditionValue, result);
			}
		}

		/// <summary>
		/// 任务记录
		/// </summary>
		protected virtual void TaskRecord(ScheduleAttribute ab, string taskDetails, string conditionInfo, OperateResult result)
		{
		}
	}
}
